import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoClient {

    public ServerSocket serverSocket = null;

    public TcpEchoClient(int id) throws IOException {
        serverSocket  = new ServerSocket(id);
    }

    public void stack() throws IOException {
        System.out.println("启动服务器");
        ExecutorService executorService = Executors.newCachedThreadPool();
        while(true) {
            //和客服端建立连接,无连接则阻塞等待
            Socket socket = serverSocket .accept();

            executorService.submit(() ->  {
                try {
                    ComnectionProcess(socket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }

    }

    public void ComnectionProcess(Socket socket) throws IOException {
                    System.out.printf("[%s:%d] 建立连接!\n",socket.getInetAddress().toString(), socket.getPort());
            try (InputStream inputStream = socket.getInputStream();
                 OutputStream outputStream = socket.getOutputStream()) {
                Scanner scanner = new Scanner(inputStream);
                PrintWriter writer = new PrintWriter(outputStream);
                while (true) {
                    if(!scanner.hasNext()) {
                        System.out.printf("[%s:%d] 断开连接!\n",socket.getInetAddress().toString(), socket.getPort());
                        break;
                    }
                    //读取请求并解析
                    String str = scanner.next();
                    //请求回应
                    String str1 = process(str);
                    //响应请求并刷新缓冲区
                    writer.println(str);
                    writer.flush();
                    //打印信息
                    System.out.printf("[%s:%d] 请求:%s 响应:%s\n", socket.getInetAddress().toString(), socket.getPort(),
                            str, str1);
                }
            }finally {
                socket.close();
            }
    }

    public String process(String str) {
        return str;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient(2000);
        client.stack();
    }
}
